"""
jackson.extjson.ext_json

Extends json to allow for transparent encoding/decoding of custom objects used in Jackson.

Specifically, adds support to json for serializing/deserializing:
    jackson.chord.Server    ep 10:43am 12/24/08
"""
import simplejson as json
from jackson.chord import Server


### Encoding

class JacksonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Server):
            dict = obj.to_dict()
            dict["__jackson.chord.Server__"] = True
            return dict
        return json.JSONEncoder.default(self, obj)

def dumps(obj, *args, **kwargs):
    kwargs["cls"] = JacksonEncoder
    return json.dumps(obj, *args, **kwargs)

### Decoding

def as_jackson_obj(dct):
    if '__jackson.chord.Server__' in dct:
        return Server(dict=dct)
    return dct

def loads(code, *args, **kwargs):
    kwargs["object_hook"] = as_jackson_obj
    return json.loads(code, *args, **kwargs)
